package com.sc.controller;

import com.sc.pojo.User;
import com.sc.service.UserService;
import com.sc.util.MD5;
import com.sc.util.UploadDownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Map;

@Controller
public class JspController {
    @Autowired
    UserService us;
    @RequestMapping("/toHome")
    public String toHome() {
        return "forward:/home.jsp";
    }
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "forward:/login.jsp";
    }
    @RequestMapping("/toRegister")
    public String toRegister() { return "forward:/register.jsp"; }
    @RequestMapping("/toProfile")
    public String toprofile() {
        return "forward:/profile.jsp";
    }
    @RequestMapping("/toEditPwd")
    public String toeditPwd() {
        return "forward:/editPwd.jsp";
    }
    @RequestMapping("/editPwd")
    public String editPwd(HttpSession session, String oldpwd, String password, Map m) {
        User u = (User) session.getAttribute("theUser");
        String pw = u.getPassword();
        if (pw.equals(MD5.MD5Code(oldpwd))) {
            u.setPassword(password);
            us.upd(u);
            return "redirect:/toHome";
        } else {
            m.put("error","原密码输入错误");
        }
        return "/admin/editPwd";
    }

    @RequestMapping("/profile")
    public String profile(User u, HttpSession session, MultipartFile myHead, HttpServletRequest req) {
        if (myHead.getOriginalFilename().length() > 0) {
            String path = req.getServletContext().getRealPath("/upload") + File.separator + u.getHeadpic();
            File f = new File(path);
            f.delete();
            u.setHeadpic(UploadDownloadUtil.upload(req, myHead));
        }
        us.upd(u);
        session.setAttribute("theUser",u);
        return "redirect:/toHome";
    }
}
